package com.media.controller;

import com.content.base.exception.XueChengPlusException;
import com.media.dto.UploadFileDto;
import com.media.service.MediaFilesService;
import com.media.vo.MediaFileVo;
import io.minio.errors.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@RestController
@RequestMapping("/upload")
@Api(tags = "媒资管理接口")
@RequiredArgsConstructor
public class MediaUploadController {

    private final MediaFilesService mediaFilesService;

    @RequestMapping(value = "/coursefile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation("普通媒资上传接口")
    public MediaFileVo courseFileUpload(@RequestPart MultipartFile filedata, @RequestParam(value = "objectName", required = false) String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //获取文件类型
        String contentType = filedata.getContentType();

        //获取文件原始名称
        String originalFilename = filedata.getOriginalFilename();

        //在当前磁盘的创建临时文件
        File tempFile = null;
        try {
            tempFile = File.createTempFile("minio", ".png");
        } catch (Exception e) {
            XueChengPlusException.cast("创建临时文件失败！");
        }


        //获取临时文件路径
        String absolutePath = tempFile.getAbsolutePath();

        try {
            //上传文件拷贝到临时文件
            filedata.transferTo(tempFile);
        } catch (IOException e) {
            XueChengPlusException.cast("拷贝临时文件失败！");
        }


        //获取文件大小
        long size = filedata.getSize();

        UploadFileDto dto = new UploadFileDto();
        dto.setFilename(originalFilename);
        dto.setFileType(contentType);
        dto.setFileSize(size);
        //todo 上传人名字  机构id
        MediaFileVo mediaFileVo = null;

        mediaFileVo = mediaFilesService.uploadFiles(dto, 6L, absolutePath,objectName);

        //删除临时文件
        tempFile.delete();
        return mediaFileVo;
    }
}
